<?php

namespace app\tools;

/**
 * 数组结构处理
 * Class NodeTree
 * @package projects\tools
 */
class NodeTree
{

    /**
     * 全部数据
     * User : Du
     * Date : 2022/3/9
     * Time : 13:49
     * @var array
     */
    public static array $allData = [];

    /**
     * 数组转树形
     * User : Du
     * Date : 2022/3/9
     * Time : 13:50
     * @param array $data
     * @return array
     */
    public static function arrayToTree(array $data): array
    {
        self::$allData = $data;
        $arr = $data[0];
        return self::getChildData($arr, $arr['id']);
    }

    /**
     * User : Du
     * Date : 2022/3/8
     * Time : 16:47
     * @param array $data
     * @param int $id
     * @return array
     */
    private static function getChildData(array $data, int $id = 0): array
    {
        $son = self::prev($id);
        if ($son) {  //
            if (isOneDimensionArray($son)) {
                $data['child_node'] = $son;
            } else {
                foreach ($son as $v) {
                    $v = self::getChildData($v, $v['id']);
                    if ($v['type'] == 3) {
                        $data['condition_nodes'][] = $v;
                    } else {
                        $data['child_node'] = $v;
                    }
                }
            }
        }
        return $data;

    }

    /**
     * 获取上级节点是此id的数据
     * User : Du
     * Date : 2022/3/8
     * Time : 16:41
     * @param int $id
     * @return array
     */
    private static function prev(int $id): array
    {
        $arr = [];
        $list = array_column(self::$allData, 'prev');
        foreach ($list as $k => $v) {
            if ($v == $id) {
                if (!$arr) {
                    $arr = self::$allData[$k];
                } elseif (isOneDimensionArray($arr)) {
                    $new = $arr;
                    $arr = [$new, self::$allData[$k]];
                } else {
                    $arr[] = self::$allData[$k];
                }
            }
        }
        return $arr;
    }

}